package com.wing.device.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.device.dao.MaintenanceExecuteDao;
import com.wing.device.model.entity.Maintenance;
import com.wing.device.model.entity.MaintenanceExecute;
import com.wing.device.model.entity.MaintenanceExecuteDetail;
import com.wing.device.model.request.MaintenanceExeDetailForm;
import com.wing.device.model.response.MaintenanceExecuteVo;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @version 1.1.0
 * @Author hz
 * @Date 2024-08-22 10:58
 **/

@Service
@Slf4j
public class DeviceMaintenanceExecuteServiceImpl extends ServiceImpl<MaintenanceExecuteDao, MaintenanceExecute> implements DeviceMaintenanceExecuteService {
    /**
     * 任务服务
     */
    @Resource
    private DeviceMaintenanceService deviceMaintenanceService;
    /**
     * 任务执行服务
     */
    @Resource
    private DeviceMaintenanceExecuteService deviceMaintenanceExecuteService;

    /**
     * 任务详情服务
     */
    @Resource
    private DeviceMaintenanceExecuteDetailService deviceMaintenanceExecuteDetailService;


    /**
     * 查询所有的任务执行情况
     *
     * @param pg
     * @param map
     * @return
     */
    @Override
    public IPage<MaintenanceExecuteVo> pageList4app(Page<MaintenanceExecuteVo> pg, Map map) {
        List<MaintenanceExecuteVo> list;
        list = baseMapper.list4app(pg, map);
        pg.setRecords(list);
        return pg;
    }

    /**
     * 处理临时任务 因为零临时任务不能被认领 无认领id
     *
     * @param form
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addTemporaryTaskBy(MaintenanceExeDetailForm form) {
        //1. 添加任务信息
        Maintenance maintenance = new Maintenance();
        String taskNo = UniqueIdGeneratorUtil.generateUniqueId("SBWB", "yyyyMMdd", 1000, 9999);
        maintenance.setTaskNo(taskNo);
        maintenance.setTaskType(form.getTaskType());
        maintenance.setStatus(MaintenanceEnum.StatusEnum.WC.getCode());
        maintenance.setTaskNature(form.getTaskNature() == null ? "" : form.getTaskNature().toString());
        maintenance.setDeviceId(Long.valueOf(form.getDeviceNo()));
        maintenance.setTaskName(form.getTaskName());
        maintenance.setMaintenanceType(Long.valueOf(form.getMaintenanceType()));
        maintenance.setDeviceLocation(form.getDeviceLocation());
        maintenance.setDepartmentId(JwtUtils.getDepartmentId());
        maintenance.setPostId((JwtUtils.getPostId()));
        maintenance.setTaskRemark(form.getTaskRemark());
        maintenance.setPreImg(form.getPreImg());
        maintenance.setPostImg(form.getPostImg());
        maintenance.setExamineType(MaintenanceEnum.AduitEnum.SHTG.getCode());
        maintenance.setExamineTime(LocalDateTime.now());
        maintenance.setCreator(JwtUtils.getLoginUserId());
        maintenance.setCreateTime(LocalDateTime.now());
        maintenance.setCreatorName(JwtUtils.getLoginUsername());
        maintenance.setModifier(JwtUtils.getLoginUserId());
        maintenance.setModifierName(JwtUtils.getLoginUsername());
        maintenance.setUpdateTime(LocalDateTime.now());
        boolean addMain = deviceMaintenanceService.save(maintenance);
        //2. 添加执行信息
        if (addMain) {
            MaintenanceExecute maintenanceExecute = new MaintenanceExecute();
            String executeNo = UniqueIdGeneratorUtil.generateUniqueId("ZXWB", "yyyyMMdd", 1000, 9999);
            maintenanceExecute.setTaskId(maintenance.getId());
            maintenanceExecute.setExecuteNo(executeNo);
            maintenanceExecute.setEndRemark(form.getEndRemark());
            maintenanceExecute.setMaterialAmount(form.getMaterialAmount());
            maintenanceExecute.setUserTime(form.getUserTime());
            maintenanceExecute.setStopTime(form.getStopTime());
            maintenanceExecute.setFaultReason(form.getFaultReason());
            maintenanceExecute.setFaultDescription(form.getFaultDescription());
            maintenanceExecute.setRepairDescription(form.getRepairDescription());
            maintenanceExecute.setRemainingProblems(form.getRemainingProblems());
            maintenanceExecute.setCreator(JwtUtils.getLoginUserId());
            maintenanceExecute.setCreateTime(LocalDateTime.now());
            maintenanceExecute.setCreatorName(JwtUtils.getLoginUsername());
            maintenanceExecute.setModifier(JwtUtils.getLoginUserId());
            maintenanceExecute.setModifierName(JwtUtils.getLoginUsername());
            maintenanceExecute.setUpdateTime(LocalDateTime.now());
            boolean addMainExecute = deviceMaintenanceExecuteService.save(maintenanceExecute);
            if (addMainExecute) {
                List<MaintenanceExecuteDetail> executeDetail = form.getExecuteDetail();
                //3. 添加物料信息
                if (!CollectionUtil.isEmpty(executeDetail)) {
                    executeDetail.stream().forEach(info -> {
                        info.setExecuteId(maintenanceExecute.getId());
                        info.setCreator(JwtUtils.getLoginUserId());
                        info.setCreateTime(LocalDateTime.now());
                        info.setCreatorName(JwtUtils.getLoginUsername());
                        info.setModifier(JwtUtils.getLoginUserId());
                        info.setModifierName(JwtUtils.getLoginUsername());
                        info.setUpdateTime(LocalDateTime.now());
                    });
                }
                boolean b = deviceMaintenanceExecuteDetailService.saveBatch(executeDetail);
                if (b) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
        return 0;
    }

    /**
     * 添加认领任务
     *
     * @param form
     * @return
     */
    @Override
    public int addGettingTaskBy(MaintenanceExeDetailForm form) {
        //认领任务已经有了任务id
        Maintenance maintenance = deviceMaintenanceService.getById(form.getTaskId());
        maintenance.setStatus(MaintenanceEnum.StatusEnum.WC.getCode());
        maintenance.setPreImg(form.getPreImg());
        maintenance.setPostImg(form.getPostImg());
        boolean b1 = deviceMaintenanceService.updateById(maintenance);
        if (b1) {
            //1. 添加任务执行记录
            MaintenanceExecute maintenanceExecute = new MaintenanceExecute();
            String executeNo = UniqueIdGeneratorUtil.generateUniqueId("ZXWB", "yyyyMMdd", 1000, 9999);
            maintenanceExecute.setTaskId(Long.valueOf(form.getTaskId()));
            maintenanceExecute.setExecuteNo(executeNo);
            maintenanceExecute.setEndRemark(form.getEndRemark());
            maintenanceExecute.setMaterialAmount(form.getMaterialAmount());
            maintenanceExecute.setUserTime(form.getUserTime());
            maintenanceExecute.setStopTime(form.getStopTime());
            maintenanceExecute.setFaultReason(form.getFaultReason());
            maintenanceExecute.setFaultDescription(form.getFaultDescription());
            maintenanceExecute.setRepairDescription(form.getRepairDescription());
            maintenanceExecute.setRemainingProblems(form.getRemainingProblems());
            maintenanceExecute.setCreator(JwtUtils.getLoginUserId());
            maintenanceExecute.setCreateTime(LocalDateTime.now());
            maintenanceExecute.setCreatorName(JwtUtils.getLoginUsername());
            maintenanceExecute.setModifier(JwtUtils.getLoginUserId());
            maintenanceExecute.setModifierName(JwtUtils.getLoginUsername());
            maintenanceExecute.setUpdateTime(LocalDateTime.now());
            boolean addMainExecute = deviceMaintenanceExecuteService.save(maintenanceExecute);
            if (addMainExecute) {
                List<MaintenanceExecuteDetail> executeDetail = form.getExecuteDetail();
                //3. 添加物料信息
                if (!CollectionUtil.isEmpty(executeDetail)) {
                    executeDetail.stream().forEach(info -> {
                        info.setExecuteId(maintenanceExecute.getId());
                        info.setCreator(JwtUtils.getLoginUserId());
                        info.setCreateTime(LocalDateTime.now());
                        info.setCreatorName(JwtUtils.getLoginUsername());
                        info.setModifier(JwtUtils.getLoginUserId());
                        info.setModifierName(JwtUtils.getLoginUsername());
                        info.setUpdateTime(LocalDateTime.now());
                    });
                }
                boolean b = deviceMaintenanceExecuteDetailService.saveBatch(executeDetail);
                if (b) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
        return 0;
    }

    /**
     * 查询我的执行记录
     * @param pg
     * @param map
     * @return
     */
    @Override
    public IPage<MaintenanceExecuteVo> pageList4app_My(Page<MaintenanceExecuteVo> pg, Map map) {
        List<MaintenanceExecuteVo> list;
        list = baseMapper.list4app_my(pg, map);
        pg.setRecords(list);
        return pg;
    }
}
